//
//  AppDelegate.m
//  GoodLuck
//
//  Created by apple on 2018/1/25.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "AppDelegate.h"
#import "GYMainTabBarController.h"
#import "GYUser.h"
#import <AlipaySDK/AlipaySDK.h>
#import "GYWelcomeViewController.h"
#import "WXApi.h"
#import <AFNetworkReachabilityManager.h>

@interface AppDelegate ()<WXApiDelegate>

/** 主要控制器 */
@property (nonatomic, strong) GYMainTabBarController *mainController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    //监听改变控制器
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateVC) name:@"changedViewController" object:nil];
    
    //监听是否需要重新登陆
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userlogin) name:userAgainLanding object:nil];
    
    //0.注册微信支付
    [WXApi registerApp:@"wx871c40551f5fe1ec"];

    //1.监测网络状态
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        self.netWork = status ==0 ? NO : YES;
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    //2.设置TabBar的文字颜色 152 152 152
    [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName:RGBColor(0, 158, 214)} forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName:RGBColor(0, 158, 214)} forState:UIControlStateSelected];//RGBColor(152, 152, 152)
    
    //3.创建可视窗口
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    //3.1判断用户是不是第一次打开APP 或则是否是APP更新
    BOOL firstShow = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstShow"];
    
    //取得沙盒中的版本号
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFBundleShortVersionString"];
    
    //取得当前的版本号
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if (!firstShow || ![oldVersion isEqualToString:currentVersion]) {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstShow"];
        [[NSUserDefaults standardUserDefaults]setObject:currentVersion forKey:@"CFBundleShortVersionString"];
        //证明是第一次打开APP 或则是版本更新
        GYWelcomeViewController *welcomeVC = [[GYWelcomeViewController alloc] initWithNibName:@"GYWelcomeViewController" bundle:nil];
        self.window.rootViewController = welcomeVC;
    }else {
        [self updateVC];
    }
    
    [self.window makeKeyAndVisible];
    
    
    return YES;
}

/**
 更新显示的控制器
 */
- (void)updateVC {
    if (!self.mainController) {
        GYMainTabBarController *main = [[GYMainTabBarController alloc] init];
        self.window.rootViewController = main;
        self.mainController = main;
    }
}

/**
 检测用户是够需要中心登陆
 */
- (void)userlogin {
    self.mainController.selectedIndex = 2;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark --  支付

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    [WXApi handleOpenURL:url delegate:self];
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"IOS8----------result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:zhifubaoPaySuccess object:resultDic];
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"IOS8==========result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    [WXApi handleOpenURL:url delegate:self];
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"IO9--result = %@",resultDic);
            //代表支付成功
            [[NSNotificationCenter defaultCenter] postNotificationName:zhifubaoPaySuccess object:resultDic];
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"IOS9=============result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}


#pragma mark -- WXApiDelegate

/*! @brief 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 *
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
-(void) onReq:(BaseReq*)req {

}



/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
-(void) onResp:(BaseResp*)resp {
   
    //WXSuccess           = 0,    /**< 成功    */
    //WXErrCodeCommon     = -1,   /**< 普通错误类型    */
    //WXErrCodeUserCancel = -2,   /**< 用户点击取消并返回    */
    //WXErrCodeSentFail   = -3,   /**< 发送失败    */
    //WXErrCodeAuthDeny   = -4,   /**< 授权失败    */
    //WXErrCodeUnsupport  = -5,   /**< 微信不支持    */
    
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp *response=(PayResp *)resp;
        switch(response.errCode){
            case WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
                [[NSNotificationCenter defaultCenter]postNotificationName:WeiXinPaySuccess object:nil];
                break;
                
            case WXErrCodeUserCancel:
                [[NSNotificationCenter defaultCenter] postNotificationName:WeiXinPayCanacel object:nil];
                break;
            
            default:
                NSLog(@"error===%d",response.errCode);
                break;
        }
    }
}

@end
